import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author wcj
 * @Date 2021/6/17 15:55
 * @Version 1.0
 */
public class SemaphoreTest {

    private static final int THRESHOLD = 30;

    private static ExecutorService executorService = Executors.newFixedThreadPool(THRESHOLD);

    private static Semaphore semaphore = new Semaphore(10);

    /**
     * Semaphore：用于多线程操作有限公有资源的情况下，限制线程的数量
     *
     * @param args
     */
    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        System.out.println("save data");
                        semaphore.release();
                    } catch (Exception e) {
                        System.out.println(e);
                    }
                }
            });
        }

        executorService.shutdown();
    }
}
